﻿using Gufa.Web.Attributes;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using System.Reflection;

namespace Gufa.Web.Filters
{
    public class UnitOfWorkFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var result = await next();
            if (result.Exception != null)
            {
                return;
            }
            var actionDes = context.ActionDescriptor as ControllerActionDescriptor;
            if (actionDes == null)
            {
                return;
            }
            var attribute = actionDes.MethodInfo.GetCustomAttribute(typeof(UnitOfWorkAttribute)) as UnitOfWorkAttribute;
            if (attribute == null)
            {
                return;
            }
            foreach (var ctx in attribute.DbContextTypes)
            {
                var dbContext = context.HttpContext.RequestServices.GetService(ctx) as DbContext;
                if (dbContext != null)
                {
                    await dbContext.SaveChangesAsync();
                }
            }
        }
    }
}
